﻿using PlayerRoles;
using PluginAPI.Core;
using PluginAPI.Core.Attributes;
using PluginAPI.Enums;
using PluginAPI.Events;
using System;
using System.Collections;
using System.Linq;
using System.Threading.Tasks;
using UnityEngine;
using Utils;


namespace Zombie.Event
{

    internal class ZombieEvent
    {
        Vector3 respawnPoint;

        bool isEnable = false;



        /// <summary>
        /// 倒计时
        /// </summary>
        IEnumerator ITimeCount()
        {
            uint count = 20;

            TimeCoroutine.Delay(10, () => Log.Info("播放倒计时"));

            yield return TimeCoroutine.Loop(20, 1,
                () =>
                {
                    string message = $"生化病毒正在寻找寄生体中......({count})s";
                    Server.SendBroadcast(message, 2, Broadcast.BroadcastFlags.Normal, true);
                    count--;
                },
               
                () =>
                {
                    string message = $"生化母体出现......";
                    Server.SendBroadcast(message, 5, Broadcast.BroadcastFlags.Normal, true);

                    // 播放音效

                    Player[] players = Player.GetPlayers().OrderBy(e=> Guid.NewGuid()).ToList().GetRange(0, 3).ToArray();
                    Array.ForEach(players, player =>
                    {
                        Vector3 position = player.Position;
                        player.SetRole(RoleTypeId.Scp0492);
                        player.Position = position + Vector3.up;
                    });
                });
        }

        /// <summary>
        /// 设置角色
        /// </summary>
        IEnumerator IReadySet()
        {
            yield return new WaitForEndOfFrame();

            Player.GetPlayers().ForEach(player =>
            {
                if (player.Role == RoleTypeId.Spectator)
                {
                    player.SetRole(RoleTypeId.Scientist);
                }

                if (player.Team == Team.ChaosInsurgency || player.Team == Team.ClassD)
                {
                    Vector3 point = player.Position;
                    player.SetRole(RoleTypeId.FacilityGuard);
                    player.Position = point + Vector3.up;
                }

                if (player.Team == Team.SCPs)
                {
                    Vector3 point = player.Position;
                    player.SetRole(RoleTypeId.Scientist);
                    player.Position = point + Vector3.up;
                }
            });
        }





        [PluginEvent(ServerEventType.RemoteAdminCommand)]
        public async void OnCommandExecuted(PlayerGameConsoleCommandExecutedEvent ev)
        {
            if (!ev.Command.StartsWith("RuleZ")) return;

            Round.IsLocked = true;

            isEnable = true;

            float x = Convert.ToSingle(ev.Arguments[0]);
            float y = Convert.ToSingle(ev.Arguments[1]);
            float z = Convert.ToSingle(ev.Arguments[2]);


            respawnPoint = new Vector3(x, y, z);

            foreach (var player in Player.GetPlayers())
            {
                int index = UnityEngine.Random.Range(0, 100);

                if (index < 10)
                {
                    player.SetRole(RoleTypeId.NtfCaptain);
                    player.RemoveItems(ItemType.KeycardMTFCaptain);
                    player.AddItem(ItemType.GrenadeFlash);
                    player.AddItem(ItemType.GrenadeHE);
                }

                if (index < 30)
                {
                    player.SetRole(RoleTypeId.NtfPrivate);
                    player.RemoveItems(ItemType.KeycardMTFPrivate);
                    player.AddItem(ItemType.GrenadeFlash);
                    player.AddItem(ItemType.GrenadeHE);
                }

                if (index < 50)
                {
                    player.SetRole(RoleTypeId.NtfSergeant);
                    player.RemoveItems(ItemType.KeycardMTFOperative);
                    player.AddItem(ItemType.GrenadeFlash);
                    player.AddItem(ItemType.GrenadeHE);
                }

                if (index < 70)
                {
                    player.SetRole(RoleTypeId.FacilityGuard);
                    player.RemoveItems(ItemType.KeycardGuard);
                    player.AddItem(ItemType.GrenadeFlash);
                    player.AddItem(ItemType.GrenadeHE);
                }

                if (index <= 100)
                {
                    player.SetRole(RoleTypeId.Scientist);
                    await Task.Delay(1200);
                    player.RemoveItems(ItemType.KeycardJanitor);
                    player.RemoveItems(ItemType.KeycardFacilityManager);
                    player.RemoveItems(ItemType.KeycardContainmentEngineer);
                    player.RemoveItems(ItemType.KeycardResearchCoordinator);
                    player.RemoveItems(ItemType.KeycardScientist);
                    player.RemoveItems(ItemType.KeycardZoneManager);
                    player.AddItem(ItemType.GunAK);
                    player.AddItem(ItemType.GrenadeFlash);
                    player.AddItem(ItemType.GrenadeHE);
                }

                player.Position = respawnPoint + Vector3.up;






                //Task.Run(async () =>
                //{
                //    uint time = 360;
                //    while (time > 0)
                //    {
                //        await Task.Delay(1000);

                //        int humans = Player.GetPlayers().FindAll(e => e.IsHuman).Count;

                //        string message = $"当前玩家：[幸存]{humans} | [感染]{Player.Count - humans} | 剩余时间：{time}";
                //        Server.SendBroadcast(message, 1, Broadcast.BroadcastFlags.Normal, true);

                //        if (humans == 0)
                //        {
                //            Server.SendBroadcast("Zombie 胜利", 5, Broadcast.BroadcastFlags.Normal, true);
                //            break;
                //        }

                //        time--;

                //        if (time == 150)
                //        {
                //            Server.SendBroadcast("空投补给已发送！", 4, Broadcast.BroadcastFlags.Normal, true);
                //            Player.GetPlayers().FindAll(e => e.IsHuman).ForEach(e => e.AddItem(ItemType.GunShotgun));
                //            await Task.Delay(4000);
                //            time-=3;
                //        }

                //        if (time == 60)
                //        {
                //            Server.SendBroadcast("空投补给已发送！", 4, Broadcast.BroadcastFlags.Normal, true);
                //            Player.GetPlayers().FindAll(e => e.IsHuman).ForEach(e => e.AddItem(ItemType.MicroHID));
                //            await Task.Delay(4000);
                //            time -= 3;
                //        }
                //    }

                //    if (Player.GetPlayers().FindAll(e => e.IsHuman).Count == 0)
                //    {
                //        Server.SendBroadcast("人类 胜利", 5, Broadcast.BroadcastFlags.Normal, true);
                //    }
                //});

  


                //for (int i = 0; i < zombies.Count; i++)
                //{
                //    Vector3 point = zombies[i].Position + Vector3.up;
                //    zombies[i].SetRole(zombieType[i], RoleChangeReason.Respawn);
                //    await Task.Delay(1000);
                //    zombies[i].Position = point;
                //} 

            }
        }

        [PluginEvent(ServerEventType.PlayerDeath)]
        public void OnPlayerDeath(PlayerDeathEvent ev)
        {
            if (!isEnable) return;


            if (ev.Attacker.IsHuman)
            {
                ev.Player.SetRole(PlayerRoles.RoleTypeId.Scp0492);
                ev.Player.Position = respawnPoint;
            }
            else
            {
                Vector3 point = ev.Player.Position;
                ev.Player.SetRole(PlayerRoles.RoleTypeId.Scp0492);

                ev.Player.Health = 1500;
                ev.Player.Position = point;
            }
        }

    }
}
